﻿using System;
using Greg.XmlEditor.Presentation.Presenters;

namespace Greg.XmlEditor.Presentation.Commands.Concrete
{
	public class SaveCommand : CommandBase
	{
		private readonly MasterPresenter presenter;
		private readonly ICommand saveAsCommand;
		private readonly IInteractionManager interaction;

		public SaveCommand(MasterPresenter presenter, ICommand saveAsCommand, IInteractionManager interaction)
		{
			this.presenter = presenter;
			this.saveAsCommand = saveAsCommand;
			this.interaction = interaction;
		}

		/// <summary>
		/// Refreshes the command state.
		/// </summary>
		public override void Refresh()
		{
			this.IsEnabled = (this.presenter.CurrentDocument != null);
		}

		/// <summary>
		/// Executes the command logics.
		/// </summary>
		public override void Invoke()
		{
			try
			{
				var document = this.presenter.CurrentDocument;

				if (!document.IsPersistent)
				{
					this.saveAsCommand.Invoke();
					return;
				}

				document.Save();
			}
			catch (Exception ex)
			{
				this.interaction.ShowError(ex.Message);
			}
		}
	}
}
